package com.punch.order.util;

import com.punch.common.exception.BusinessException;
import com.punch.common.feign.FeignClassService;
import com.punch.common.redis.lock.RedissonDistributedLock;
import com.punch.common.utils.SpringUtil;
import com.punch.common.vo.course.classes.FeignClassVO;
import com.punch.order.exception.OrderExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;

import java.util.concurrent.TimeUnit;

/**
 * @className: RedissonUtil
 * @description: redisson锁工具类
 * @author: wujj
 * @date: 2020/12/09 20:22
 **/
@Slf4j
public class RedissonUtil {

    private static RedissonDistributedLock redissonDistributedLock = SpringUtil.getBean(RedissonDistributedLock.class);
    private static FeignClassService feignClassService = SpringUtil.getBean(FeignClassService.class);

    /**
     * 根据课程班级信息
     *
     * @param courseClassId 班级课程id
     * @return AppClassVO
     */
    public static FeignClassVO redissonLock(Long courseClassId) {
        String key = "classId:create-order:" + courseClassId;
        RLock lock = null;
        FeignClassVO classVO;
        try {
            lock = redissonDistributedLock.tryLock(key, 5, TimeUnit.SECONDS);
            classVO = feignClassService.getFeignClassById(courseClassId);
            if (classVO == null || classVO.getCourseClassId() == null) {
                throw new BusinessException(OrderExceptionEnum.FEIGN_ERROR.getCode(), "远程调用课程服务失败");
            }
        } catch (InterruptedException e) {
            log.error("Redisson获取分布式锁异常,异常信息:{}", e.getMessage());
            throw new RuntimeException(e);
        } finally {
            redissonDistributedLock.unlock(lock);
            log.info("Redisson分布式锁释放锁:{},ThreadName :{}", key, Thread.currentThread().getName());
        }
        return classVO;
    }
}
